import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import moment from 'moment';
import CaipanForm from './components/CaipanForm';

import {
  Form,
  Input,
  DatePicker,
  Icon,
  Button,
  Radio,
  Upload,
  message,
  Popconfirm,
  Checkbox,
  InputNumber,
  Tabs,
} from 'antd';
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;

const timeOptions = [
  { label: '上午', value: 'morning' },
  { label: '下午', value: 'afternoon' },
  { label: '晚上', value: 'night' },
];

@connect(({ gameList, place, loading }) => ({
  gameList,
  place,
  submitting: loading.effects['gameList/modifyGame'],
}))
@Form.create()
export default class GameModifyForm extends PureComponent {
  state = {
    curProject: {},
    checkedValues: [],
    curData: {},
  };

  componentDidMount = () => {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');

    const id = pathArray[3];
    this.setState({
      id,
    });
    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: this.afterFindById,
    });

    dispatch({
      type: 'gameList/findProjectDict',
    });
  };

  afterFindById = () => {
    const item = this.props.gameList.modifyItem;
    if (!item.id) {
      this.props.dispatch(
        routerRedux.push({
          pathname: '/badminton/list-play',
        })
      );
    }
    item.signDate = [];
    item.signDate[0] = moment(item.signStartDate);
    item.signDate[1] = moment(item.signEndDate);

    item.gameDate = [];
    item.gameDate[0] = moment(item.startDate);
    item.gameDate[1] = moment(item.endDate);

    item.timePhase = item.timePhase ? item.timePhase.split(',') : [];

    delete item.signStartDate;
    delete item.signEndDate;
    delete item.startDate;
    delete item.endDate;

    this.setState({
      isPublic: item.isPublic,
      checkedValues: item.timePhase,
      curModifyGame: item,
    });

    this.props.dispatch({
      type: 'place/findGameCaipan',
      payload: {},
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.startDate = values.gameDate[0];
        values.endDate = values.gameDate[1];

        values.signStartDate = values.signDate[0];
        values.signEndDate = values.signDate[1];

        values.timePhase = values.timePhase.join(',');

        delete values.gameDate;
        delete values.signDate;

        this.props.dispatch({
          type: 'gameList/modifyGame',
          payload: values,
        });
      }
    });
  };

  handlePublicChange = e => {
    this.setState({
      isPublic: e.target.value,
    });
  };

  viewRole = () => {
    const { modifyItem } = this.props.gameList;
    modifyItem && window.open('/bgms/gameInfo/rule?gameId=' + modifyItem.id, 'GET');
  };

  setGameRole = () => {
    this.props.dispatch({
      type: 'gameList/findById',
      payload: this.state.id,
      callback: this.afterFindById,
    });
  };

  delelteGameRole = () => {
    this.props.dispatch({
      type: 'gameList/removeGameRole',
      payload: this.state.id,
      callback: () => {
        message.success('规程删除成功');
        this.props.dispatch({
          type: 'gameList/findById',
          payload: this.state.id,
          callback: this.afterFindById,
        });
      },
    });
  };

  generateUploadProps = () => {
    const _this = this;
    const { modifyItem } = this.props.gameList;
    return {
      name: 'file',
      action: `/bgms/gameInfo/upload?gameId=${modifyItem.id}`,
      accept: '.pdf',
      onChange(info) {
        if (info.file.status !== 'uploading') {
          //console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          const fileName = info.file.response.fileId;
          _this.setGameRole(fileName);
          message.success(`${info.file.name} 上传成功`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败.`);
        }
      },
    };
  };

  checkChange = checkedValues => {
    console.log(checkedValues);
    this.setState({
      checkedValues,
    });
  };

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const curData = this.state.curModifyGame;
    const { caipanModalVisible } = this.state;
    const {
      place: { placeList, caipanList, curCaipan },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const caipanMethod = {
      handleAdd: this.caipanhandler,
      handleModalVisible: this.caipanHandleModalVisible,
    };

    function disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    }

    return (
      <Fragment>
        <Tabs
          tabBarExtraContent={
            <Button style={{ marginRight: 5 }} onClick={() => this.showCaipanModifyModal()}>
              裁判管理
            </Button>
          }
        >
          <TabPane tab="基本信息" key="infoT">
            <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 30 }}>
              {getFieldDecorator('id', { initialValue: curData && curData.id })(
                <Input type="hidden" readOnly />
              )}
              <FormItem {...formItemLayout} label="赛事名称">
                {getFieldDecorator('title', {
                  rules: [
                    {
                      required: true,
                      message: '请输入赛事名称',
                    },
                  ],
                  initialValue: curData && curData.title,
                })(<Input placeholder="赛事名称" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="赛事规程">
                <div>
                  {curData &&
                    curData.gameRole && (
                      <span>
                        <Button onClick={() => this.viewRole()}>查看规程</Button>
                        <Popconfirm
                          title="是否确定删除规程?删除完成后将刷新赛事数据，未保存的修改将丢弃。"
                          onConfirm={this.delelteGameRole}
                          okText="Yes"
                          cancelText="No"
                        >
                          <Button style={{ marginLeft: 10 }}>删除规程</Button>
                        </Popconfirm>
                      </span>
                    )}
                  <Upload {...this.generateUploadProps()} style={{ marginLeft: 10 }}>
                    <Button>
                      <Icon type="upload" />
                      上传规程
                    </Button>
                  </Upload>
                </div>
              </FormItem>
              {getFieldDecorator('code', { initialValue: curData && curData.code })(
                <Input type="hidden" readOnly />
              )}
              <FormItem {...formItemLayout} label="赛事状态">
                {getFieldDecorator('status', {})(<Input readOnly />)}
              </FormItem>
              <FormItem {...formItemLayout} label="举办单位">
                {getFieldDecorator('owner', {
                  rules: [
                    {
                      required: true,
                      message: '请输入举办单位',
                    },
                  ],
                  initialValue: curData && curData.owner,
                })(<Input placeholder="赛事名称" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="联系电话">
                {getFieldDecorator('tel', {
                  rules: [
                    {
                      required: true,
                      message: '请输入联系电话',
                    },
                  ],
                  initialValue: curData && curData.tel,
                })(<Input placeholder="联系电话" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="比赛地点">
                {getFieldDecorator('position', {
                  rules: [
                    {
                      required: true,
                      message: '请输入比赛地点',
                    },
                  ],
                  initialValue: curData && curData.position,
                })(<Input placeholder="比赛地点" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="场地数量">
                {getFieldDecorator('placeCount', {
                  rules: [
                    {
                      required: true,
                      message: '请输入场地数量',
                    },
                  ],
                  initialValue: curData && curData.placeCount,
                })(<Input placeholder="场地数量" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="报名起止日期">
                {getFieldDecorator('signDate', {
                  rules: [
                    {
                      required: true,
                      message: '请选择报名起止日期',
                    },
                  ],
                  initialValue: curData && curData.signDate,
                })(
                  <RangePicker
                    disabledDate={disabledDate}
                    style={{ width: '100%' }}
                    placeholder={['开始日期', '结束日期']}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="比赛起止日期">
                {getFieldDecorator('gameDate', {
                  rules: [
                    {
                      required: true,
                      message: '请选择赛事起止日期',
                    },
                  ],
                  initialValue: curData && curData.gameDate,
                })(
                  <RangePicker
                    disabledDate={disabledDate}
                    style={{ width: '100%' }}
                    placeholder={['开始日期', '结束日期']}
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="比赛时段">
                {getFieldDecorator('timePhase', {
                  rules: [{ required: true, message: '请选择比赛时段' }],
                  initialValue: curData && curData.timePhase,
                })(<CheckboxGroup options={timeOptions} onChange={this.checkChange} />)}
              </FormItem>
              {this.state.checkedValues.map(item => (
                <FormItem
                  key={item}
                  {...formItemLayout}
                  label={item === 'morning' ? '上午' : item === 'afternoon' ? '下午' : '晚上'}
                >
                  {getFieldDecorator(item, {
                    rules: [{ required: true, message: '请输入比赛场数' }],
                    initialValue: curData && curData[item],
                  })(<InputNumber min={1} max={100} formatter={value => `${value} 场`} />)}
                </FormItem>
              ))}
              <FormItem {...formItemLayout} label="赛事简介">
                {getFieldDecorator('gameDesc', {
                  rules: [
                    {
                      required: true,
                      message: '请输入赛事简介',
                    },
                  ],
                  initialValue: curData && curData.gameDesc,
                })(<TextArea style={{ minHeight: 32 }} placeholder="赛事简介" rows={4} />)}
              </FormItem>
              {/* <FormItem
            {...formItemLayout}
            label="目标公开"
            help="不公开的赛事，必须要的邀请码才可以报名"
          >
            <div>
              {getFieldDecorator('isPublic', {
                initialValue: false,
              })(
                <Radio.Group name="isPublic" onChange={this.handlePublicChange}>
                  <Radio value={false}>不公开</Radio>
                  <Radio value={true}>公开</Radio>
                </Radio.Group>
              )}
            </div>
          </FormItem>
          {!this.state.isPublic && (
            <FormItem {...formItemLayout} label="邀请码">
              <div>
                {getFieldDecorator('inviteCode', {
                  rules: [
                    {
                      max: 10,
                      message: '邀请码最多10位',
                    },
                  ],
                })(<Input placeholder="请输入邀请码" />)}
              </div>
            </FormItem>
          )} */}
              <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                <Button type="primary" htmlType="submit" loading={submitting}>
                  保存
                </Button>
                <Link to="/badminton/list-play">
                  <Button style={{ marginLeft: 8 }}>返回赛事列表</Button>
                </Link>
              </FormItem>
            </Form>
          </TabPane>
        </Tabs>
        <CaipanForm
          {...caipanMethod}
          modalVisible={caipanModalVisible}
          caiapnList={caipanList}
          selectByTel={this.handleCaipanFindByTel}
          deleteMethod={this.handleCaipanDelete}
          curData={curCaipan}
        />
      </Fragment>
    );
  }
  showCaipanModifyModal = data => {
    this.setState({
      caipanModalVisible: true,
    });
  };

  handleCaipanAdd = fields => {
    this.props.dispatch({
      type: 'place/addCaipan',
      payload: fields,
      callback: () => {
        //this.caipanHandleModalVisible(false)
        this.props.dispatch({
          type: 'place/changeState',
          payload: { curCaipan: {} },
        });
        this.props.dispatch({
          type: 'place/findGameCaipan',
          payload: {},
        });
        message.success('裁判添加成功');
      },
    });
    //this.CaipanHandleModalVisible();
  };

  handleCaipanFindByTel = tel => {
    this.props.dispatch({
      type: 'place/findCaipanByTel',
      payload: tel,
    });
  };

  handleCaipanDelete = id => {
    this.props.dispatch({
      type: 'place/deleteCaipan',
      payload: id,
      callback: () => {
        this.props.dispatch({
          type: 'place/findGameCaipan',
          payload: {},
        });
        message.success('裁判删除成功');
      },
    });
  };

  caipanhandler = values => {
    this.handleCaipanAdd(values);
  };

  caipanHandleModalVisible = flag => {
    this.setState({
      caipanModalVisible: !!flag,
    });
    this.props.dispatch({
      type: 'place/changeState',
      payload: { curCaipan: {} },
    });
  };
}
